package com.lz.sports.dialog

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lz.library.dialog.BaseDialogFragment
import com.lz.library.extension.click
import com.lz.sports.R
import com.lz.sports.databinding.DialogWarningBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class WarningDialog : BaseDialogFragment<DialogWarningBinding>() {

    companion object {
        fun show(activity: FragmentActivity, content: String, title: String = "", requestCode: Int = -1): WarningDialog {
            val dialog = WarningDialog().also {
                it.arguments = Bundle().apply {
                    putString("title", title)
                    putString("content", content)
                    putInt("requestCode", requestCode)
                }
            }
            dialog.setFrom(true)
            dialog.show(activity.supportFragmentManager)
            return dialog
        }

        fun show(fragment: Fragment, content: String, title: String = "", requestCode: Int = -1): WarningDialog {
            val dialog = WarningDialog().also {
                it.arguments = Bundle().apply {
                    putString("title", title)
                    putString("content", content)
                    putInt("requestCode", requestCode)
                }
            }
            dialog.show(fragment.childFragmentManager)
            return dialog
        }
    }

    override fun getLayoutRes(): Int = R.layout.dialog_warning

    override fun initData(v: View, savedState: Bundle?) {
        lifecycleScope.launch {
            arrayOf(binding.tvConfirm, binding.tvCancel).click().collect {
                when (it.id) {
                    R.id.tv_cancel -> dismiss()
                    R.id.tv_confirm -> {
                        val requestCode = arguments!!.getInt("requestCode")
                        if (isFromActivity()) {
                            if (context is OnWarningConfirmListener) {
                                (context as OnWarningConfirmListener).onConfirm(this@WarningDialog, requestCode)
                            }
                        } else {
                            if (parentFragment is OnWarningConfirmListener) {
                                (parentFragment as OnWarningConfirmListener).onConfirm(this@WarningDialog, requestCode)
                            }
                        }
                    }
                }
            }
        }
        val title = arguments?.getString("title")
        if (!TextUtils.isEmpty(title)) binding.tvTitle.text = title
        binding.tvContent.text = arguments?.getString("content")
    }

    interface OnWarningConfirmListener {

        fun onConfirm(dialog: WarningDialog, requestCode: Int)
    }
}